function [Z, H] = my_orth(F)
%This function makes the factors in the matrix F uncorrelated. It also
%provides the rotation matrix H such that Z=F*H
%Input: 
%F=T x K matrix of correlated factors
%Output:
%Z=T x K matrix of uncorrelated factors
%H=K x K rotation matrix
T=size(F,1);
K=size(F,2);
H=eye(K);
Z=zeros(T,K);
c=ones(T,1);
Z(:,1)=F(:,1);
for k=1:K-1
    X=[c F(:,1:k)];
    coeff=inv(X'*X)*X'*F(:,k+1);
    Xfitted=X(:,2:end)*coeff(2:end);
    Z(:,k+1)=F(:,k+1)-Xfitted;
    H(k+1,1:k)=-coeff(2:end)';
end
%Normalized factors in Z to have positive average
for k=1:size(Z,2)
    if (mean(Z(:,k))<0)
        Z(:,k)=(-1)*Z(:,k);
        H(k,:)=(-1)*H(k,:);
    end
end 
H=H';
